package fr.epsi.action;

import java.util.List;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

import fr.epsi.model.Brand;
import fr.epsi.service.BrandService;

@SuppressWarnings("serial")
public class BrandAction extends ActionSupport implements Preparable {
    private BrandService service;
    private List<Brand> brands;
    private Brand brand;
    private Integer id;

    public BrandAction(BrandService service) {
        this.service = service;
    }

    public String execute() {
        this.brands = service.findAll();
        return Action.SUCCESS;
    }

    public String save() {
    	String c = brand.getCountry();
    	String n = brand.getName();
    	if (!c.matches("[a-zA-Z]{1,30}") | n.equals("[a-zA-Z]{1,30}") ) {
    		return Action.ERROR;
    	}
        this.service.save(brand);
        this.brand = new Brand();
        return execute();
    }

    public String remove() {
        service.remove(id);
        return execute();
    }

    public List<Brand> getBrands() {
        return brands;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void prepare() throws Exception {
        if (id != null)
            brand = service.find(id);
        if (brands == null)
        	brands = service.findAll();
    }

    public Brand getBrand() {
        return brand;
    }

    public void setBrand(Brand brand) {
        this.brand = brand;
    }
    
}
